package com.eascs.fp.uc.controller;

import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.fp.common.entity.MemberEntity;
import com.eascs.fp.common.vo.ModelResult;
import com.eascs.fp.uc.server.MemberService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.captcha.controller.CaptchaBuilder;
import com.eascs.web.captcha.patchca.service.Captcha;
import com.eascs.web.context.ResponseContext;

@RestController
public class CommonRestController  extends BaseRestController{
	
	private CaptchaBuilder captchaBuilder = new CaptchaBuilder();
	@Autowired
	private MemberService memberService;
	
	
	@RequestMapping(value = "/common/getCaptcha")
	public void buidCaptchaImage(HttpServletResponse resp) {
		ResponseContext.setContentType(MediaType.IMAGE_PNG_VALUE);
		ResponseContext.setDateHeader("Expries", 0);
		ResponseContext.setHeader("Pragma", "no-cache");
		Captcha captcha = captchaBuilder.buildCaptcha();
		CaptchaBuilder.SESSION_CAPTCHA.setValue(captcha.getChallenge());
		try {
			ImageIO.write(captcha.getImage(), "png", ResponseContext.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/common/checkCaptcha")
	@ResponseBody
	public BaseRestResult<Boolean> checkCaptcha(String captcha){
		String captchaCode=CaptchaBuilder.SESSION_CAPTCHA.getValue();
		if(!captchaCode.equals(captcha)){
			return BaseRestResult.buildRestResult(false);
		}
		return BaseRestResult.buildRestResult(true);
	}
	@RequestMapping(value = "/common/checkUser")
	@ResponseBody
	public BaseRestResult<Boolean> checkUser(String mobile){
		MemberEntity member=new MemberEntity();
		member.setMobile(mobile);
		ModelResult<MemberEntity> queryResult=memberService.queryMemberEntity(member);
		if (!queryResult.isSuccess() || queryResult.getModel() != null) {
			return BaseRestResult.buildRestResult(true);
		}
		return BaseRestResult.buildRestResult(false);
	}
	
	
	
}
